3 * Base class for resource loading system.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @author Roan Kattouw
22 * @author Trevor Parscal
25 use MediaWiki\MediaWikiServices
;
26 use Psr\Log\LoggerAwareInterface
;
27 use Psr\Log\LoggerInterface
;
28 use Psr\Log\NullLogger
;
29 use Wikimedia\Rdbms\DBConnectionError
;
30 use Wikimedia\WrappedString
;
33 * Dynamic JavaScript and CSS resource loading system.
35 * Most of the documentation is on the MediaWiki documentation wiki starting at:
36 * https://www.mediawiki.org/wiki/ResourceLoader
38 class ResourceLoader
implements LoggerAwareInterface
{
40 const CACHE_VERSION
= 8;
43 protected static $debugMode = null;
46 * Module name/ResourceLoaderModule object pairs
49 protected $modules = [];
52 * Associative array mapping module name to info associative array
55 protected $moduleInfos = [];
57 /** @var Config $config */
61 * List of module names that contain QUnit test suites
64 protected $testSuiteModuleNames = [];
67 * E.g. [ 'source-id' => 'http://.../load.php' ]
70 protected $sources = [];
73 * Errors accumulated during current respond() call.
76 protected $errors = [];
79 * List of extra HTTP response headers provided by loaded modules.
81 * Populated by makeModuleResponse().
85 protected $extraHeaders = [];
88 * @var MessageBlobStore
93 * @var LoggerInterface
97 /** @var string JavaScript / CSS pragma to disable minification. **/
98 const FILTER_NOMIN
= '/*@nomin*/';
101 * Load information stored in the database about modules.
103 * This method grabs modules dependencies from the database and updates modules
106 * This is not inside the module code because it is much faster to
107 * request all of the information at once than it is to have each module
108 * requests its own information. This sacrifice of modularity yields a substantial
109 * performance improvement.
111 * @param array $moduleNames List of module names to preload information for
112 * @param ResourceLoaderContext $context Context to load the information within
114 public function preloadModuleInfo( array $moduleNames, ResourceLoaderContext
$context ) {
115 if ( !$moduleNames ) {
116 // Or else Database*::select() will explode, plus it's cheaper!
119 $dbr = wfGetDB( DB_REPLICA
);
120 $lang = $context->getLanguage();
122 // Batched version of ResourceLoaderModule::getFileDependencies
123 $vary = ResourceLoaderModule
::getVary( $context );
124 $res = $dbr->select( 'module_deps', [ 'md_module', 'md_deps' ], [
125 'md_module' => $moduleNames,
130 // Prime in-object cache for file dependencies
131 $modulesWithDeps = [];
132 foreach ( $res as $row ) {
133 $module = $this->getModule( $row->md_module
);
135 $module->setFileDependencies( $context, ResourceLoaderModule
::expandRelativePaths(
136 json_decode( $row->md_deps
, true )
138 $modulesWithDeps[] = $row->md_module
;
141 // Register the absence of a dependency row too
142 foreach ( array_diff( $moduleNames, $modulesWithDeps ) as $name ) {
143 $module = $this->getModule( $name );
145 $this->getModule( $name )->setFileDependencies( $context, [] );
149 // Batched version of ResourceLoaderWikiModule::getTitleInfo
150 ResourceLoaderWikiModule
::preloadTitleInfo( $context, $dbr, $moduleNames );
152 // Prime in-object cache for message blobs for modules with messages
154 foreach ( $moduleNames as $name ) {
155 $module = $this->getModule( $name );
156 if ( $module && $module->getMessages() ) {
157 $modules[$name] = $module;
160 $store = $this->getMessageBlobStore();
161 $blobs = $store->getBlobs( $modules, $lang );
162 foreach ( $blobs as $name => $blob ) {
163 $modules[$name]->setMessageBlob( $blob, $lang );
168 * Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
170 * Available filters are:
172 * - minify-js \see JavaScriptMinifier::minify
173 * - minify-css \see CSSMin::minify
175 * If $data is empty, only contains whitespace or the filter was unknown,
176 * $data is returned unmodified.
178 * @param string $filter Name of filter to run
179 * @param string $data Text to filter, such as JavaScript or CSS text
180 * @param array $options Keys:
181 * - (bool) cache: Whether to allow caching this data. Default: true.
182 * @return string Filtered data, or a comment containing an error message
184 public static function filter( $filter, $data, array $options = [] ) {
185 if ( strpos( $data, self
::FILTER_NOMIN
) !== false ) {
189 if ( isset( $options['cache'] ) && $options['cache'] === false ) {
190 return self
::applyFilter( $filter, $data );
193 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
194 $cache = ObjectCache
::getLocalServerInstance( CACHE_ANYTHING
);
196 $key = $cache->makeGlobalKey(
197 'resourceloader-filter',
203 $result = $cache->get( $key );
204 if ( $result === false ) {
205 $stats->increment( "resourceloader_cache.$filter.miss" );
206 $result = self
::applyFilter( $filter, $data );
207 $cache->set( $key, $result, 24 * 3600 );
209 $stats->increment( "resourceloader_cache.$filter.hit" );
211 if ( $result === null ) {
219 private static function applyFilter( $filter, $data ) {
220 $data = trim( $data );
223 $data = ( $filter === 'minify-css' )
224 ? CSSMin
::minify( $data )
225 : JavaScriptMinifier
::minify( $data );
226 } catch ( Exception
$e ) {
227 MWExceptionHandler
::logException( $e );
235 * Register core modules and runs registration hooks.
236 * @param Config|null $config
237 * @param LoggerInterface|null $logger [optional]
239 public function __construct( Config
$config = null, LoggerInterface
$logger = null ) {
240 $this->logger
= $logger ?
: new NullLogger();
243 wfDeprecated( __METHOD__
. ' without a Config instance', '1.34' );
244 $config = MediaWikiServices
::getInstance()->getMainConfig();
246 $this->config
= $config;
248 // Add 'local' source first
249 $this->addSource( 'local', $config->get( 'LoadScript' ) );
251 // Special module that always exists
252 $this->register( 'startup', [ 'class' => ResourceLoaderStartUpModule
::class ] );
254 $this->setMessageBlobStore( new MessageBlobStore( $this, $this->logger
) );
260 public function getConfig() {
261 return $this->config
;
266 * @param LoggerInterface $logger
268 public function setLogger( LoggerInterface
$logger ) {
269 $this->logger
= $logger;
274 * @return LoggerInterface
276 public function getLogger() {
277 return $this->logger
;
282 * @return MessageBlobStore
284 public function getMessageBlobStore() {
285 return $this->blobStore
;
290 * @param MessageBlobStore $blobStore
292 public function setMessageBlobStore( MessageBlobStore
$blobStore ) {
293 $this->blobStore
= $blobStore;
297 * Register a module with the ResourceLoader system.
299 * @param string|array[] $name Module name as a string or, array of module info arrays
301 * @param array|null $info Module info array. When using the first parameter to register
302 * multiple modules at once, this parameter is optional.
303 * @throws MWException If a duplicate module registration is attempted
304 * @throws MWException If a module name contains illegal characters (pipes or commas)
305 * @throws InvalidArgumentException If the module info is not an array
307 public function register( $name, $info = null ) {
308 $moduleSkinStyles = $this->config
->get( 'ResourceModuleSkinStyles' );
310 // Allow multiple modules to be registered in one call
311 $registrations = is_array( $name ) ?
$name : [ $name => $info ];
312 foreach ( $registrations as $name => $info ) {
313 // Warn on duplicate registrations
314 if ( isset( $this->moduleInfos
[$name] ) ) {
315 // A module has already been registered by this name
316 $this->logger
->warning(
317 'ResourceLoader duplicate registration warning. ' .
318 'Another module has already been registered as ' . $name
323 if ( !self
::isValidModuleName( $name ) ) {
324 throw new MWException( "ResourceLoader module name '$name' is invalid, "
325 . "see ResourceLoader::isValidModuleName()" );
327 if ( !is_array( $info ) ) {
328 throw new InvalidArgumentException(
329 'Invalid module info for "' . $name . '": expected array, got ' . gettype( $info )
334 $this->moduleInfos
[$name] = $info;
336 // Last-minute changes
337 // Apply custom skin-defined styles to existing modules.
338 if ( $this->isFileModule( $name ) ) {
339 foreach ( $moduleSkinStyles as $skinName => $skinStyles ) {
340 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
341 if ( isset( $this->moduleInfos
[$name]['skinStyles'][$skinName] ) ) {
345 // If $name is preceded with a '+', the defined style files will be added to 'default'
346 // skinStyles, otherwise 'default' will be ignored as it normally would be.
347 if ( isset( $skinStyles[$name] ) ) {
348 $paths = (array)$skinStyles[$name];
350 } elseif ( isset( $skinStyles['+' . $name] ) ) {
351 $paths = (array)$skinStyles['+' . $name];
352 $styleFiles = isset( $this->moduleInfos
[$name]['skinStyles']['default'] ) ?
353 (array)$this->moduleInfos
[$name]['skinStyles']['default'] :
359 // Add new file paths, remapping them to refer to our directories and not use settings
360 // from the module we're modifying, which come from the base definition.
361 list( $localBasePath, $remoteBasePath ) =
362 ResourceLoaderFileModule
::extractBasePaths( $skinStyles );
364 foreach ( $paths as $path ) {
365 $styleFiles[] = new ResourceLoaderFilePath( $path, $localBasePath, $remoteBasePath );
368 $this->moduleInfos
[$name]['skinStyles'][$skinName] = $styleFiles;
375 * @internal For use by ServiceWiring only
376 * @codeCoverageIgnore
378 public function registerTestModules() {
381 if ( $this->config
->get( 'EnableJavaScriptTest' ) !== true ) {
382 throw new MWException( 'Attempt to register JavaScript test modules '
383 . 'but <code>$wgEnableJavaScriptTest</code> is false. '
384 . 'Edit your <code>LocalSettings.php</code> to enable it.' );
387 // This has a 'qunit' key for compat with the below hook.
388 $testModulesMeta = [ 'qunit' => [] ];
390 // Get test suites from extensions
391 // Avoid PHP 7.1 warning from passing $this by reference
393 Hooks
::run( 'ResourceLoaderTestModules', [ &$testModulesMeta, &$rl ] );
394 $extRegistry = ExtensionRegistry
::getInstance();
395 // In case of conflict, the deprecated hook has precedence.
396 $testModules = $testModulesMeta['qunit'] +
$extRegistry->getAttribute( 'QUnitTestModules' );
398 $testSuiteModuleNames = [];
399 foreach ( $testModules as $name => &$module ) {
400 // Turn any single-module dependency into an array
401 if ( isset( $module['dependencies'] ) && is_string( $module['dependencies'] ) ) {
402 $module['dependencies'] = [ $module['dependencies'] ];
405 // Ensure the testrunner loads before any test suites
406 $module['dependencies'][] = 'test.mediawiki.qunit.testrunner';
408 // Keep track of the test suites to load on SpecialJavaScriptTest
409 $testSuiteModuleNames[] = $name;
412 // Core test suites (their names have further precedence).
413 $testModules = ( include "$IP/tests/qunit/QUnitTestResources.php" ) +
$testModules;
414 $testSuiteModuleNames[] = 'test.mediawiki.qunit.suites';
416 $this->register( $testModules );
417 $this->testSuiteModuleNames
= $testSuiteModuleNames;
421 * Add a foreign source of modules.
423 * Source IDs are typically the same as the Wiki ID or database name (e.g. lowercase a-z).
425 * @param array|string $id Source ID (string), or [ id1 => loadUrl, id2 => loadUrl, ... ]
426 * @param string|array|null $loadUrl load.php url (string), or array with loadUrl key for
427 * backwards-compatibility.
428 * @throws MWException
430 public function addSource( $id, $loadUrl = null ) {
431 // Allow multiple sources to be registered in one call
432 if ( is_array( $id ) ) {
433 foreach ( $id as $key => $value ) {
434 $this->addSource( $key, $value );
439 // Disallow duplicates
440 if ( isset( $this->sources
[$id] ) ) {
441 throw new MWException(
442 'ResourceLoader duplicate source addition error. ' .
443 'Another source has already been registered as ' . $id
447 // Pre 1.24 backwards-compatibility
448 if ( is_array( $loadUrl ) ) {
449 if ( !isset( $loadUrl['loadScript'] ) ) {
450 throw new MWException(
451 __METHOD__
. ' was passed an array with no "loadScript" key.'
455 $loadUrl = $loadUrl['loadScript'];
458 $this->sources
[$id] = $loadUrl;
462 * Get a list of module names.
464 * @return array List of module names
466 public function getModuleNames() {
467 return array_keys( $this->moduleInfos
);
471 * Get a list of module names with QUnit test suites.
473 * @internal For use by SpecialJavaScriptTest only
475 * @codeCoverageIgnore
477 public function getTestSuiteModuleNames() {
478 return $this->testSuiteModuleNames
;
482 * Check whether a ResourceLoader module is registered
485 * @param string $name
488 public function isModuleRegistered( $name ) {
489 return isset( $this->moduleInfos
[$name] );
493 * Get the ResourceLoaderModule object for a given module name.
495 * If an array of module parameters exists but a ResourceLoaderModule object has not
496 * yet been instantiated, this method will instantiate and cache that object such that
497 * subsequent calls simply return the same object.
499 * @param string $name Module name
500 * @return ResourceLoaderModule|null If module has been registered, return a
501 * ResourceLoaderModule instance. Otherwise, return null.
503 public function getModule( $name ) {
504 if ( !isset( $this->modules
[$name] ) ) {
505 if ( !isset( $this->moduleInfos
[$name] ) ) {
509 // Construct the requested module object
510 $info = $this->moduleInfos
[$name];
511 if ( isset( $info['factory'] ) ) {
512 /** @var ResourceLoaderModule $object */
513 $object = call_user_func( $info['factory'], $info );
515 $class = $info['class'] ?? ResourceLoaderFileModule
::class;
516 /** @var ResourceLoaderModule $object */
517 $object = new $class( $info );
519 $object->setConfig( $this->getConfig() );
520 $object->setLogger( $this->logger
);
521 $object->setName( $name );
522 $this->modules
[$name] = $object;
525 return $this->modules
[$name];
529 * Whether the module is a ResourceLoaderFileModule (including subclasses).
531 * @param string $name Module name
534 protected function isFileModule( $name ) {
535 if ( !isset( $this->moduleInfos
[$name] ) ) {
538 $info = $this->moduleInfos
[$name];
539 return !isset( $info['factory'] ) && (
540 // The implied default for 'class' is ResourceLoaderFileModule
541 !isset( $info['class'] ) ||
543 $info['class'] === ResourceLoaderFileModule
::class ||
544 is_subclass_of( $info['class'], ResourceLoaderFileModule
::class )
549 * Get the list of sources.
551 * @return array Like [ id => load.php url, ... ]
553 public function getSources() {
554 return $this->sources
;
558 * Get the URL to the load.php endpoint for the given
559 * ResourceLoader source
562 * @param string $source
563 * @throws MWException On an invalid $source name
566 public function getLoadScript( $source ) {
567 if ( !isset( $this->sources
[$source] ) ) {
568 throw new MWException( "The $source source was never registered in ResourceLoader." );
570 return $this->sources
[$source];
575 * @param string $value
576 * @return string Hash
578 public static function makeHash( $value ) {
579 $hash = hash( 'fnv132', $value );
580 return Wikimedia\base_convert
( $hash, 16, 36, 7 );
584 * Add an error to the 'errors' array and log it.
586 * @private For internal use by ResourceLoader and ResourceLoaderStartUpModule.
588 * @param Exception $e
590 * @param array $context
592 public function outputErrorAndLog( Exception
$e, $msg, array $context = [] ) {
593 MWExceptionHandler
::logException( $e );
594 $this->logger
->warning(
596 $context +
[ 'exception' => $e ]
598 $this->errors
[] = self
::formatExceptionNoComment( $e );
602 * Helper method to get and combine versions of multiple modules.
605 * @param ResourceLoaderContext $context
606 * @param string[] $moduleNames List of known module names
607 * @return string Hash
609 public function getCombinedVersion( ResourceLoaderContext
$context, array $moduleNames ) {
610 if ( !$moduleNames ) {
613 $hashes = array_map( function ( $module ) use ( $context ) {
615 return $this->getModule( $module )->getVersionHash( $context );
616 } catch ( Exception
$e ) {
617 // If modules fail to compute a version, don't fail the request (T152266)
618 // and still compute versions of other modules.
619 $this->outputErrorAndLog( $e,
620 'Calculating version for "{module}" failed: {exception}',
628 return self
::makeHash( implode( '', $hashes ) );
632 * Get the expected value of the 'version' query parameter.
634 * This is used by respond() to set a short Cache-Control header for requests with
635 * information newer than the current server has. This avoids pollution of edge caches.
636 * Typically during deployment. (T117587)
638 * This MUST match return value of `mw.loader#getCombinedVersion()` client-side.
641 * @param ResourceLoaderContext $context
642 * @return string Hash
644 public function makeVersionQuery( ResourceLoaderContext
$context ) {
645 // As of MediaWiki 1.28, the server and client use the same algorithm for combining
646 // version hashes. There is no technical reason for this to be same, and for years the
647 // implementations differed. If getCombinedVersion in PHP (used for StartupModule and
648 // E-Tag headers) differs in the future from getCombinedVersion in JS (used for 'version'
649 // query parameter), then this method must continue to match the JS one.
651 foreach ( $context->getModules() as $name ) {
652 if ( !$this->getModule( $name ) ) {
653 // If a versioned request contains a missing module, the version is a mismatch
654 // as the client considered a module (and version) we don't have.
657 $moduleNames[] = $name;
659 return $this->getCombinedVersion( $context, $moduleNames );
663 * Output a response to a load request, including the content-type header.
665 * @param ResourceLoaderContext $context Context in which a response should be formed
667 public function respond( ResourceLoaderContext
$context ) {
668 // Buffer output to catch warnings. Normally we'd use ob_clean() on the
669 // top-level output buffer to clear warnings, but that breaks when ob_gzhandler
670 // is used: ob_clean() will clear the GZIP header in that case and it won't come
671 // back for subsequent output, resulting in invalid GZIP. So we have to wrap
672 // the whole thing in our own output buffer to be sure the active buffer
673 // doesn't use ob_gzhandler.
674 // See https://bugs.php.net/bug.php?id=36514
677 $this->measureResponseTime( RequestContext
::getMain()->getTiming() );
679 // Find out which modules are missing and instantiate the others
682 foreach ( $context->getModules() as $name ) {
683 $module = $this->getModule( $name );
685 // Do not allow private modules to be loaded from the web.
686 // This is a security issue, see T36907.
687 if ( $module->getGroup() === 'private' ) {
688 $this->logger
->debug( "Request for private module '$name' denied" );
689 $this->errors
[] = "Cannot show private module \"$name\"";
692 $modules[$name] = $module;
699 // Preload for getCombinedVersion() and for batch makeModuleResponse()
700 $this->preloadModuleInfo( array_keys( $modules ), $context );
701 } catch ( Exception
$e ) {
702 $this->outputErrorAndLog( $e, 'Preloading module info failed: {exception}' );
705 // Combine versions to propagate cache invalidation
708 $versionHash = $this->getCombinedVersion( $context, array_keys( $modules ) );
709 } catch ( Exception
$e ) {
710 $this->outputErrorAndLog( $e, 'Calculating version hash failed: {exception}' );
713 // See RFC 2616 § 3.11 Entity Tags
714 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
715 $etag = 'W/"' . $versionHash . '"';
717 // Try the client-side cache first
718 if ( $this->tryRespondNotModified( $context, $etag ) ) {
719 return; // output handled (buffers cleared)
722 // Use file cache if enabled and available...
723 if ( $this->config
->get( 'UseFileCache' ) ) {
724 $fileCache = ResourceFileCache
::newFromContext( $context );
725 if ( $this->tryRespondFromFileCache( $fileCache, $context, $etag ) ) {
726 return; // output handled
732 // Generate a response
733 $response = $this->makeModuleResponse( $context, $modules, $missing );
735 // Capture any PHP warnings from the output buffer and append them to the
736 // error list if we're in debug mode.
737 if ( $context->getDebug() ) {
738 $warnings = ob_get_contents();
739 if ( strlen( $warnings ) ) {
740 $this->errors
[] = $warnings;
744 // Consider saving the response to file cache (unless there are errors).
748 ResourceFileCache
::useFileCache( $context )
750 if ( $fileCache->isCacheWorthy() ) {
751 // There were enough hits, save the response to the cache
752 $fileCache->saveText( $response );
754 $fileCache->incrMissesRecent( $context->getRequest() );
758 $this->sendResponseHeaders( $context, $etag, (bool)$this->errors
, $this->extraHeaders
);
760 // Remove the output buffer and output the response
763 if ( $context->getImageObj() && $this->errors
) {
764 // We can't show both the error messages and the response when it's an image.
765 $response = implode( "\n\n", $this->errors
);
766 } elseif ( $this->errors
) {
767 $errorText = implode( "\n\n", $this->errors
);
768 $errorResponse = self
::makeComment( $errorText );
769 if ( $context->shouldIncludeScripts() ) {
770 $errorResponse .= 'if (window.console && console.error) {'
771 . Xml
::encodeJsCall( 'console.error', [ $errorText ] )
775 // Prepend error info to the response
776 $response = $errorResponse . $response;
783 protected function measureResponseTime( Timing
$timing ) {
784 DeferredUpdates
::addCallableUpdate( function () use ( $timing ) {
785 $measure = $timing->measure( 'responseTime', 'requestStart', 'requestShutdown' );
786 if ( $measure !== false ) {
787 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
788 $stats->timing( 'resourceloader.responseTime', $measure['duration'] * 1000 );
794 * Send main response headers to the client.
796 * Deals with Content-Type, CORS (for stylesheets), and caching.
798 * @param ResourceLoaderContext $context
799 * @param string $etag ETag header value
800 * @param bool $errors Whether there are errors in the response
801 * @param string[] $extra Array of extra HTTP response headers
804 protected function sendResponseHeaders(
805 ResourceLoaderContext
$context, $etag, $errors, array $extra = []
807 \MediaWiki\HeaderCallback
::warnIfHeadersSent();
808 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
809 // Use a short cache expiry so that updates propagate to clients quickly, if:
810 // - No version specified (shared resources, e.g. stylesheets)
811 // - There were errors (recover quickly)
812 // - Version mismatch (T117587, T47877)
813 if ( is_null( $context->getVersion() )
815 ||
$context->getVersion() !== $this->makeVersionQuery( $context )
817 $maxage = $rlMaxage['unversioned']['client'];
818 $smaxage = $rlMaxage['unversioned']['server'];
819 // If a version was specified we can use a longer expiry time since changing
820 // version numbers causes cache misses
822 $maxage = $rlMaxage['versioned']['client'];
823 $smaxage = $rlMaxage['versioned']['server'];
825 if ( $context->getImageObj() ) {
826 // Output different headers if we're outputting textual errors.
828 header( 'Content-Type: text/plain; charset=utf-8' );
830 $context->getImageObj()->sendResponseHeaders( $context );
832 } elseif ( $context->getOnly() === 'styles' ) {
833 header( 'Content-Type: text/css; charset=utf-8' );
834 header( 'Access-Control-Allow-Origin: *' );
836 header( 'Content-Type: text/javascript; charset=utf-8' );
838 // See RFC 2616 § 14.19 ETag
839 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
840 header( 'ETag: ' . $etag );
841 if ( $context->getDebug() ) {
842 // Do not cache debug responses
843 header( 'Cache-Control: private, no-cache, must-revalidate' );
844 header( 'Pragma: no-cache' );
846 header( "Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
847 $exp = min( $maxage, $smaxage );
848 header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $exp +
time() ) );
850 foreach ( $extra as $header ) {
856 * Respond with HTTP 304 Not Modified if appropiate.
858 * If there's an If-None-Match header, respond with a 304 appropriately
859 * and clear out the output buffer. If the client cache is too old then do nothing.
861 * @param ResourceLoaderContext $context
862 * @param string $etag ETag header value
863 * @return bool True if HTTP 304 was sent and output handled
865 protected function tryRespondNotModified( ResourceLoaderContext
$context, $etag ) {
866 // See RFC 2616 § 14.26 If-None-Match
867 // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
868 $clientKeys = $context->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
);
869 // Never send 304s in debug mode
870 if ( $clientKeys !== false && !$context->getDebug() && in_array( $etag, $clientKeys ) ) {
871 // There's another bug in ob_gzhandler (see also the comment at
872 // the top of this function) that causes it to gzip even empty
873 // responses, meaning it's impossible to produce a truly empty
874 // response (because the gzip header is always there). This is
875 // a problem because 304 responses have to be completely empty
876 // per the HTTP spec, and Firefox behaves buggily when they're not.
877 // See also https://bugs.php.net/bug.php?id=51579
878 // To work around this, we tear down all output buffering before
880 wfResetOutputBuffers( /* $resetGzipEncoding = */ true );
882 HttpStatus
::header( 304 );
884 $this->sendResponseHeaders( $context, $etag, false );
891 * Send out code for a response from file cache if possible.
893 * @param ResourceFileCache $fileCache Cache object for this request URL
894 * @param ResourceLoaderContext $context Context in which to generate a response
895 * @param string $etag ETag header value
896 * @return bool If this found a cache file and handled the response
898 protected function tryRespondFromFileCache(
899 ResourceFileCache
$fileCache,
900 ResourceLoaderContext
$context,
903 $rlMaxage = $this->config
->get( 'ResourceLoaderMaxage' );
904 // Buffer output to catch warnings.
906 // Get the maximum age the cache can be
907 $maxage = is_null( $context->getVersion() )
908 ?
$rlMaxage['unversioned']['server']
909 : $rlMaxage['versioned']['server'];
910 // Minimum timestamp the cache file must have
911 $good = $fileCache->isCacheGood( wfTimestamp( TS_MW
, time() - $maxage ) );
913 try { // RL always hits the DB on file cache miss...
914 wfGetDB( DB_REPLICA
);
915 } catch ( DBConnectionError
$e ) { // ...check if we need to fallback to cache
916 $good = $fileCache->isCacheGood(); // cache existence check
920 $ts = $fileCache->cacheTimestamp();
921 // Send content type and cache headers
922 $this->sendResponseHeaders( $context, $etag, false );
923 $response = $fileCache->fetchText();
924 // Capture any PHP warnings from the output buffer and append them to the
925 // response in a comment if we're in debug mode.
926 if ( $context->getDebug() ) {
927 $warnings = ob_get_contents();
928 if ( strlen( $warnings ) ) {
929 $response = self
::makeComment( $warnings ) . $response;
932 // Remove the output buffer and output the response
934 echo $response . "\n/* Cached {$ts} */";
935 return true; // cache hit
940 return false; // cache miss
944 * Generate a CSS or JS comment block.
946 * Only use this for public data, not error message details.
948 * @param string $text
951 public static function makeComment( $text ) {
952 $encText = str_replace( '*/', '* /', $text );
953 return "/*\n$encText\n*/\n";
957 * Handle exception display.
959 * @param Exception $e Exception to be shown to the user
960 * @return string Sanitized text in a CSS/JS comment that can be returned to the user
962 public static function formatException( $e ) {
963 return self
::makeComment( self
::formatExceptionNoComment( $e ) );
967 * Handle exception display.
970 * @param Exception $e Exception to be shown to the user
971 * @return string Sanitized text that can be returned to the user
973 protected static function formatExceptionNoComment( $e ) {
974 global $wgShowExceptionDetails;
976 if ( !$wgShowExceptionDetails ) {
977 return MWExceptionHandler
::getPublicLogMessage( $e );
980 return MWExceptionHandler
::getLogMessage( $e ) .
982 MWExceptionHandler
::getRedactedTraceAsString( $e );
986 * Generate code for a response.
988 * Calling this method also populates the `errors` and `headers` members,
989 * later used by respond().
991 * @param ResourceLoaderContext $context Context in which to generate a response
992 * @param ResourceLoaderModule[] $modules List of module objects keyed by module name
993 * @param string[] $missing List of requested module names that are unregistered (optional)
994 * @return string Response data
996 public function makeModuleResponse( ResourceLoaderContext
$context,
997 array $modules, array $missing = []
1002 if ( $modules === [] && $missing === [] ) {
1004 /* This file is the Web entry point for MediaWiki's ResourceLoader:
1005 <https://www.mediawiki.org/wiki/ResourceLoader>. In this request,
1006 no modules were requested. Max made me put this here. */
1010 $image = $context->getImageObj();
1012 $data = $image->getImageData( $context );
1013 if ( $data === false ) {
1015 $this->errors
[] = 'Image generation failed';
1020 foreach ( $missing as $name ) {
1021 $states[$name] = 'missing';
1024 $filter = $context->getOnly() === 'styles' ?
'minify-css' : 'minify-js';
1026 foreach ( $modules as $name => $module ) {
1028 $content = $module->getModuleContent( $context );
1029 $implementKey = $name . '@' . $module->getVersionHash( $context );
1032 if ( isset( $content['headers'] ) ) {
1033 $this->extraHeaders
= array_merge( $this->extraHeaders
, $content['headers'] );
1037 switch ( $context->getOnly() ) {
1039 $scripts = $content['scripts'];
1040 if ( is_string( $scripts ) ) {
1041 // Load scripts raw...
1042 $strContent = $scripts;
1043 } elseif ( is_array( $scripts ) ) {
1044 // ...except when $scripts is an array of URLs or an associative array
1045 $strContent = self
::makeLoaderImplementScript( $implementKey, $scripts, [], [], [] );
1049 $styles = $content['styles'];
1050 // We no longer separate into media, they are all combined now with
1051 // custom media type groups into @media .. {} sections as part of the css string.
1052 // Module returns either an empty array or a numerical array with css strings.
1053 $strContent = isset( $styles['css'] ) ?
implode( '', $styles['css'] ) : '';
1056 $scripts = $content['scripts'] ??
'';
1057 if ( is_string( $scripts ) ) {
1058 if ( $name === 'site' ||
$name === 'user' ) {
1059 // Legacy scripts that run in the global scope without a closure.
1060 // mw.loader.implement will use globalEval if scripts is a string.
1061 // Minify manually here, because general response minification is
1062 // not effective due it being a string literal, not a function.
1063 if ( !$context->getDebug() ) {
1064 $scripts = self
::filter( 'minify-js', $scripts ); // T107377
1067 $scripts = new XmlJsCode( $scripts );
1070 $strContent = self
::makeLoaderImplementScript(
1073 $content['styles'] ??
[],
1074 isset( $content['messagesBlob'] ) ?
new XmlJsCode( $content['messagesBlob'] ) : [],
1075 $content['templates'] ??
[]
1080 if ( !$context->getDebug() ) {
1081 $strContent = self
::filter( $filter, $strContent );
1083 // In debug mode, separate each response by a new line.
1084 // For example, between 'mw.loader.implement();' statements.
1085 $strContent = $this->ensureNewline( $strContent );
1088 if ( $context->getOnly() === 'scripts' ) {
1089 // Use a linebreak between module scripts (T162719)
1090 $out .= $this->ensureNewline( $strContent );
1092 $out .= $strContent;
1095 } catch ( Exception
$e ) {
1096 $this->outputErrorAndLog( $e, 'Generating module package failed: {exception}' );
1098 // Respond to client with error-state instead of module implementation
1099 $states[$name] = 'error';
1100 unset( $modules[$name] );
1104 // Update module states
1105 if ( $context->shouldIncludeScripts() && !$context->getRaw() ) {
1106 if ( $modules && $context->getOnly() === 'scripts' ) {
1107 // Set the state of modules loaded as only scripts to ready as
1108 // they don't have an mw.loader.implement wrapper that sets the state
1109 foreach ( $modules as $name => $module ) {
1110 $states[$name] = 'ready';
1114 // Set the state of modules we didn't respond to with mw.loader.implement
1116 $stateScript = self
::makeLoaderStateScript( $states );
1117 if ( !$context->getDebug() ) {
1118 $stateScript = self
::filter( 'minify-js', $stateScript );
1120 // Use a linebreak between module script and state script (T162719)
1121 $out = $this->ensureNewline( $out ) . $stateScript;
1123 } elseif ( $states ) {
1124 $this->errors
[] = 'Problematic modules: '
1125 . self
::encodeJsonForScript( $states );
1132 * Ensure the string is either empty or ends in a line break
1133 * @param string $str
1136 private function ensureNewline( $str ) {
1137 $end = substr( $str, -1 );
1138 if ( $end === false ||
$end === '' ||
$end === "\n" ) {
1145 * Get names of modules that use a certain message.
1147 * @param string $messageKey
1148 * @return array List of module names
1150 public function getModulesByMessage( $messageKey ) {
1152 foreach ( $this->getModuleNames() as $moduleName ) {
1153 $module = $this->getModule( $moduleName );
1154 if ( in_array( $messageKey, $module->getMessages() ) ) {
1155 $moduleNames[] = $moduleName;
1158 return $moduleNames;
1162 * Return JS code that calls mw.loader.implement with given module properties.
1164 * @param string $name Module name or implement key (format "`[name]@[version]`")
1165 * @param XmlJsCode|array|string $scripts Code as XmlJsCode (to be wrapped in a closure),
1166 * list of URLs to JavaScript files, string of JavaScript for `$.globalEval`, or array with
1167 * 'files' and 'main' properties (see ResourceLoaderModule::getScript())
1168 * @param mixed $styles Array of CSS strings keyed by media type, or an array of lists of URLs
1169 * to CSS files keyed by media type
1170 * @param mixed $messages List of messages associated with this module. May either be an
1171 * associative array mapping message key to value, or a JSON-encoded message blob containing
1172 * the same data, wrapped in an XmlJsCode object.
1173 * @param array $templates Keys are name of templates and values are the source of
1175 * @throws MWException
1176 * @return string JavaScript code
1178 protected static function makeLoaderImplementScript(
1179 $name, $scripts, $styles, $messages, $templates
1181 if ( $scripts instanceof XmlJsCode
) {
1182 if ( $scripts->value
=== '' ) {
1184 } elseif ( self
::inDebugMode() ) {
1185 $scripts = new XmlJsCode( "function ( $, jQuery, require, module ) {\n{$scripts->value}\n}" );
1187 $scripts = new XmlJsCode( 'function($,jQuery,require,module){' . $scripts->value
. '}' );
1189 } elseif ( is_array( $scripts ) && isset( $scripts['files'] ) ) {
1190 $files = $scripts['files'];
1191 foreach ( $files as $path => &$file ) {
1192 // $file is changed (by reference) from a descriptor array to the content of the file
1193 // All of these essentially do $file = $file['content'];, some just have wrapping around it
1194 if ( $file['type'] === 'script' ) {
1195 // Multi-file modules only get two parameters ($ and jQuery are being phased out)
1196 if ( self
::inDebugMode() ) {
1197 $file = new XmlJsCode( "function ( require, module ) {\n{$file['content']}\n}" );
1199 $file = new XmlJsCode( 'function(require,module){' . $file['content'] . '}' );
1202 $file = $file['content'];
1205 $scripts = XmlJsCode
::encodeObject( [
1206 'main' => $scripts['main'],
1207 'files' => XmlJsCode
::encodeObject( $files, self
::inDebugMode() )
1208 ], self
::inDebugMode() );
1209 } elseif ( !is_string( $scripts ) && !is_array( $scripts ) ) {
1210 throw new MWException( 'Invalid scripts error. Array of URLs or string of code expected.' );
1213 // mw.loader.implement requires 'styles', 'messages' and 'templates' to be objects (not
1214 // arrays). json_encode considers empty arrays to be numerical and outputs "[]" instead
1215 // of "{}". Force them to objects.
1223 self
::trimArray( $module );
1225 return Xml
::encodeJsCall( 'mw.loader.implement', $module, self
::inDebugMode() );
1229 * Returns JS code which, when called, will register a given list of messages.
1231 * @param mixed $messages Either an associative array mapping message key to value, or a
1232 * JSON-encoded message blob containing the same data, wrapped in an XmlJsCode object.
1233 * @return string JavaScript code
1235 public static function makeMessageSetScript( $messages ) {
1236 return 'mw.messages.set('
1237 . self
::encodeJsonForScript( (object)$messages )
1242 * Combines an associative array mapping media type to CSS into a
1243 * single stylesheet with "@media" blocks.
1245 * @param array $stylePairs Array keyed by media type containing (arrays of) CSS strings
1248 public static function makeCombinedStyles( array $stylePairs ) {
1250 foreach ( $stylePairs as $media => $styles ) {
1251 // ResourceLoaderFileModule::getStyle can return the styles
1252 // as a string or an array of strings. This is to allow separation in
1254 $styles = (array)$styles;
1255 foreach ( $styles as $style ) {
1256 $style = trim( $style );
1257 // Don't output an empty "@media print { }" block (T42498)
1258 if ( $style !== '' ) {
1259 // Transform the media type based on request params and config
1260 // The way that this relies on $wgRequest to propagate request params is slightly evil
1261 $media = OutputPage
::transformCssMedia( $media );
1263 if ( $media === '' ||
$media == 'all' ) {
1265 } elseif ( is_string( $media ) ) {
1266 $out[] = "@media $media {\n" . str_replace( "\n", "\n\t", "\t" . $style ) . "}";
1276 * Wrapper around json_encode that avoids needless escapes,
1277 * and pretty-prints in debug mode.
1281 * @param bool|string|array $data
1282 * @return string JSON
1284 public static function encodeJsonForScript( $data ) {
1285 // Keep output as small as possible by disabling needless escape modes
1286 // that PHP uses by default.
1287 // However, while most module scripts are only served on HTTP responses
1288 // for JavaScript, some modules can also be embedded in the HTML as inline
1289 // scripts. This, and the fact that we sometimes need to export strings
1290 // containing user-generated content and labels that may genuinely contain
1291 // a sequences like "</script>", we need to encode either '/' or '<'.
1292 // By default PHP escapes '/'. Let's escape '<' instead which is less common
1293 // and allows URLs to mostly remain readable.
1294 $jsonFlags = JSON_UNESCAPED_SLASHES |
1295 JSON_UNESCAPED_UNICODE |
1298 if ( self
::inDebugMode() ) {
1299 $jsonFlags |
= JSON_PRETTY_PRINT
;
1301 return json_encode( $data, $jsonFlags );
1305 * Returns a JS call to mw.loader.state, which sets the state of one
1306 * ore more modules to a given value. Has two calling conventions:
1308 * - ResourceLoader::makeLoaderStateScript( $name, $state ):
1309 * Set the state of a single module called $name to $state
1311 * - ResourceLoader::makeLoaderStateScript( [ $name => $state, ... ] ):
1312 * Set the state of modules with the given names to the given states
1314 * @param array|string $states
1315 * @param string|null $state
1316 * @return string JavaScript code
1318 public static function makeLoaderStateScript( $states, $state = null ) {
1319 if ( !is_array( $states ) ) {
1320 $states = [ $states => $state ];
1322 return 'mw.loader.state('
1323 . self
::encodeJsonForScript( $states )
1327 private static function isEmptyObject( stdClass
$obj ) {
1328 foreach ( $obj as $key => $value ) {
1335 * Remove empty values from the end of an array.
1337 * Values considered empty:
1341 * - new XmlJsCode( '{}' )
1342 * - new stdClass() // (object) []
1344 * @param array $array
1346 private static function trimArray( array &$array ) {
1347 $i = count( $array );
1349 if ( $array[$i] === null
1350 ||
$array[$i] === []
1351 ||
( $array[$i] instanceof XmlJsCode
&& $array[$i]->value
=== '{}' )
1352 ||
( $array[$i] instanceof stdClass
&& self
::isEmptyObject( $array[$i] ) )
1354 unset( $array[$i] );
1362 * Returns JS code which calls mw.loader.register with the given
1368 * ResourceLoader::makeLoaderRegisterScript( [
1369 * [ $name1, $version1, $dependencies1, $group1, $source1, $skip1 ],
1370 * [ $name2, $version2, $dependencies1, $group2, $source2, $skip2 ],
1377 * @param array $modules Array of module registration arrays, each containing
1378 * - string: module name
1379 * - string: module version
1380 * - array|null: List of dependencies (optional)
1381 * - string|null: Module group (optional)
1382 * - string|null: Name of foreign module source, or 'local' (optional)
1383 * - string|null: Script body of a skip function (optional)
1384 * @return string JavaScript code
1386 public static function makeLoaderRegisterScript( array $modules ) {
1387 // Optimisation: Transform dependency names into indexes when possible
1388 // to produce smaller output. They are expanded by mw.loader.register on
1389 // the other end using resolveIndexedDependencies().
1391 foreach ( $modules as $i => &$module ) {
1392 // Build module name index
1393 $index[$module[0]] = $i;
1395 foreach ( $modules as &$module ) {
1396 if ( isset( $module[2] ) ) {
1397 foreach ( $module[2] as &$dependency ) {
1398 if ( isset( $index[$dependency] ) ) {
1399 // Replace module name in dependency list with index
1400 $dependency = $index[$dependency];
1406 array_walk( $modules, [ self
::class, 'trimArray' ] );
1408 return 'mw.loader.register('
1409 . self
::encodeJsonForScript( $modules )
1414 * Returns JS code which calls mw.loader.addSource() with the given
1415 * parameters. Has two calling conventions:
1417 * - ResourceLoader::makeLoaderSourcesScript( $id, $properties ):
1418 * Register a single source
1420 * - ResourceLoader::makeLoaderSourcesScript( [ $id1 => $loadUrl, $id2 => $loadUrl, ... ] );
1421 * Register sources with the given IDs and properties.
1423 * @param string|array $sources Source ID
1424 * @param string|null $loadUrl load.php url
1425 * @return string JavaScript code
1427 public static function makeLoaderSourcesScript( $sources, $loadUrl = null ) {
1428 if ( !is_array( $sources ) ) {
1429 $sources = [ $sources => $loadUrl ];
1431 return 'mw.loader.addSource('
1432 . self
::encodeJsonForScript( $sources )
1437 * Wraps JavaScript code to run after the startup module.
1439 * @param string $script JavaScript code
1440 * @return string JavaScript code
1442 public static function makeLoaderConditionalScript( $script ) {
1443 // Adds a function to lazy-created RLQ
1444 return '(RLQ=window.RLQ||[]).push(function(){' .
1445 trim( $script ) . '});';
1449 * Wraps JavaScript code to run after a required module.
1452 * @param string|string[] $modules Module name(s)
1453 * @param string $script JavaScript code
1454 * @return string JavaScript code
1456 public static function makeInlineCodeWithModule( $modules, $script ) {
1457 // Adds an array to lazy-created RLQ
1458 return '(RLQ=window.RLQ||[]).push(['
1459 . self
::encodeJsonForScript( $modules ) . ','
1460 . 'function(){' . trim( $script ) . '}'
1465 * Returns an HTML script tag that runs given JS code after startup and base modules.
1467 * The code will be wrapped in a closure, and it will be executed by ResourceLoader's
1468 * startup module if the client has adequate support for MediaWiki JavaScript code.
1470 * @param string $script JavaScript code
1471 * @param string|null $nonce [optional] Content-Security-Policy nonce
1472 * (from OutputPage::getCSPNonce)
1473 * @return string|WrappedString HTML
1475 public static function makeInlineScript( $script, $nonce = null ) {
1476 $js = self
::makeLoaderConditionalScript( $script );
1478 if ( $nonce === null ) {
1479 wfWarn( __METHOD__
. " did not get nonce. Will break CSP" );
1480 } elseif ( $nonce !== false ) {
1481 // If it was false, CSP is disabled, so no nonce attribute.
1482 // Nonce should be only base64 characters, so should be safe,
1483 // but better to be safely escaped than sorry.
1484 $escNonce = ' nonce="' . htmlspecialchars( $nonce ) . '"';
1487 return new WrappedString(
1488 Html
::inlineScript( $js, $nonce ),
1489 "<script$escNonce>(RLQ=window.RLQ||[]).push(function(){",
1495 * Returns JS code which will set the MediaWiki configuration array to
1498 * @param array $configuration List of configuration values keyed by variable name
1499 * @return string JavaScript code
1502 public static function makeConfigSetScript( array $configuration ) {
1503 $js = Xml
::encodeJsCall(
1508 if ( $js === false ) {
1510 'JSON serialization of config data failed. ' .
1511 'This usually means the config data is not valid UTF-8.'
1513 MWExceptionHandler
::logException( $e );
1514 $js = Xml
::encodeJsCall( 'mw.log.error', [ $e->__toString() ] );
1520 * Convert an array of module names to a packed query string.
1522 * For example, `[ 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' ]`
1523 * becomes `'foo.bar,baz|bar.baz,quux'`.
1525 * This process is reversed by ResourceLoader::expandModuleNames().
1526 * See also mw.loader#buildModulesString() which is a port of this, used
1527 * on the client-side.
1529 * @param array $modules List of module names (strings)
1530 * @return string Packed query string
1532 public static function makePackedModulesString( $modules ) {
1533 $moduleMap = []; // [ prefix => [ suffixes ] ]
1534 foreach ( $modules as $module ) {
1535 $pos = strrpos( $module, '.' );
1536 $prefix = $pos === false ?
'' : substr( $module, 0, $pos );
1537 $suffix = $pos === false ?
$module : substr( $module, $pos +
1 );
1538 $moduleMap[$prefix][] = $suffix;
1542 foreach ( $moduleMap as $prefix => $suffixes ) {
1543 $p = $prefix === '' ?
'' : $prefix . '.';
1544 $arr[] = $p . implode( ',', $suffixes );
1546 return implode( '|', $arr );
1550 * Expand a string of the form `jquery.foo,bar|jquery.ui.baz,quux` to
1551 * an array of module names like `[ 'jquery.foo', 'jquery.bar',
1552 * 'jquery.ui.baz', 'jquery.ui.quux' ]`.
1554 * This process is reversed by ResourceLoader::makePackedModulesString().
1557 * @param string $modules Packed module name list
1558 * @return array Array of module names
1560 public static function expandModuleNames( $modules ) {
1562 $exploded = explode( '|', $modules );
1563 foreach ( $exploded as $group ) {
1564 if ( strpos( $group, ',' ) === false ) {
1565 // This is not a set of modules in foo.bar,baz notation
1566 // but a single module
1569 // This is a set of modules in foo.bar,baz notation
1570 $pos = strrpos( $group, '.' );
1571 if ( $pos === false ) {
1572 // Prefixless modules, i.e. without dots
1573 $retval = array_merge( $retval, explode( ',', $group ) );
1575 // We have a prefix and a bunch of suffixes
1576 $prefix = substr( $group, 0, $pos ); // 'foo'
1577 $suffixes = explode( ',', substr( $group, $pos +
1 ) ); // [ 'bar', 'baz' ]
1578 foreach ( $suffixes as $suffix ) {
1579 $retval[] = "$prefix.$suffix";
1588 * Determine whether debug mode was requested
1589 * Order of priority is 1) request param, 2) cookie, 3) $wg setting
1592 public static function inDebugMode() {
1593 if ( self
::$debugMode === null ) {
1594 global $wgRequest, $wgResourceLoaderDebug;
1595 self
::$debugMode = $wgRequest->getFuzzyBool( 'debug',
1596 $wgRequest->getCookie( 'resourceLoaderDebug', '', $wgResourceLoaderDebug )
1599 return self
::$debugMode;
1603 * Reset static members used for caching.
1605 * Global state and $wgRequest are evil, but we're using it right
1606 * now and sometimes we need to be able to force ResourceLoader to
1607 * re-evaluate the context because it has changed (e.g. in the test suite).
1609 * @internal For use by unit tests
1610 * @codeCoverageIgnore
1612 public static function clearCache() {
1613 self
::$debugMode = null;
1617 * Build a load.php URL
1620 * @param string $source Name of the ResourceLoader source
1621 * @param ResourceLoaderContext $context
1622 * @param array $extraQuery
1623 * @return string URL to load.php. May be protocol-relative if $wgLoadScript is, too.
1625 public function createLoaderURL( $source, ResourceLoaderContext
$context,
1628 $query = self
::createLoaderQuery( $context, $extraQuery );
1629 $script = $this->getLoadScript( $source );
1631 return wfAppendQuery( $script, $query );
1635 * Helper for createLoaderURL()
1638 * @see makeLoaderQuery
1639 * @param ResourceLoaderContext $context
1640 * @param array $extraQuery
1643 protected static function createLoaderQuery( ResourceLoaderContext
$context, $extraQuery = [] ) {
1644 return self
::makeLoaderQuery(
1645 $context->getModules(),
1646 $context->getLanguage(),
1647 $context->getSkin(),
1648 $context->getUser(),
1649 $context->getVersion(),
1650 $context->getDebug(),
1651 $context->getOnly(),
1652 $context->getRequest()->getBool( 'printable' ),
1653 $context->getRequest()->getBool( 'handheld' ),
1659 * Build a query array (array representation of query string) for load.php. Helper
1660 * function for createLoaderURL().
1662 * @param array $modules
1663 * @param string $lang
1664 * @param string $skin
1665 * @param string|null $user
1666 * @param string|null $version
1667 * @param bool $debug
1668 * @param string|null $only
1669 * @param bool $printable
1670 * @param bool $handheld
1671 * @param array $extraQuery
1674 public static function makeLoaderQuery( $modules, $lang, $skin, $user = null,
1675 $version = null, $debug = false, $only = null, $printable = false,
1676 $handheld = false, $extraQuery = []
1679 'modules' => self
::makePackedModulesString( $modules ),
1681 // Keep urls short by omitting query parameters that
1682 // match the defaults assumed by ResourceLoaderContext.
1683 // Note: This relies on the defaults either being insignificant or forever constant,
1684 // as otherwise cached urls could change in meaning when the defaults change.
1685 if ( $lang !== ResourceLoaderContext
::DEFAULT_LANG
) {
1686 $query['lang'] = $lang;
1688 if ( $skin !== ResourceLoaderContext
::DEFAULT_SKIN
) {
1689 $query['skin'] = $skin;
1691 if ( $debug === true ) {
1692 $query['debug'] = 'true';
1694 if ( $user !== null ) {
1695 $query['user'] = $user;
1697 if ( $version !== null ) {
1698 $query['version'] = $version;
1700 if ( $only !== null ) {
1701 $query['only'] = $only;
1704 $query['printable'] = 1;
1707 $query['handheld'] = 1;
1709 $query +
= $extraQuery;
1711 // Make queries uniform in order
1717 * Check a module name for validity.
1719 * Module names may not contain pipes (|), commas (,) or exclamation marks (!) and can be
1720 * at most 255 bytes.
1722 * @param string $moduleName Module name to check
1723 * @return bool Whether $moduleName is a valid module name
1725 public static function isValidModuleName( $moduleName ) {
1726 return strcspn( $moduleName, '!,|', 0, 255 ) === strlen( $moduleName );
1730 * Returns LESS compiler set up for use with MediaWiki
1733 * @param array $vars Associative array of variables that should be used
1734 * for compilation. Since 1.32, this method no longer automatically includes
1735 * global LESS vars from ResourceLoader::getLessVars (T191937).
1736 * @throws MWException
1737 * @return Less_Parser
1739 public function getLessCompiler( $vars = [] ) {
1741 // When called from the installer, it is possible that a required PHP extension
1742 // is missing (at least for now; see T49564). If this is the case, throw an
1743 // exception (caught by the installer) to prevent a fatal error later on.
1744 if ( !class_exists( 'Less_Parser' ) ) {
1745 throw new MWException( 'MediaWiki requires the less.php parser' );
1748 $parser = new Less_Parser
;
1749 $parser->ModifyVars( $vars );
1750 $parser->SetImportDirs( [
1751 "$IP/resources/src/mediawiki.less/" => '',
1753 $parser->SetOption( 'relativeUrls', false );
1759 * Get global LESS variables.
1762 * @deprecated since 1.32 Use ResourceLoderModule::getLessVars() instead.
1763 * @return array Map of variable names to string CSS values.
1765 public function getLessVars() {